package com.tanhua.admin.service;


import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.*;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ManageService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private MovementApi movementApi;

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private ManageApi manageApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 分页查询所有的探花用户信息
     *   userInfo
     */
    public PageResult users(Integer page, Integer pagesize) {
        //1、调用API分页查询UserInfo  IPage
        IPage iPage = userInfoApi.findAll(page,pagesize); //分页pagebean
        //2、构造PageResult
        return new PageResult(page,pagesize,iPage.getTotal(),iPage.getRecords());
    }

    //根据id查询用户详情
    public UserInfo findUserById(Long userId) {
        return userInfoApi.findById(userId);
    }

    //根据用户id，分页查询视频列表
    public PageResult findVideos(Long userId, Integer page, Integer pagesize) {
        //1、调用API查询，返回分页数据  PageResult （分页列表，总数）  --- List<Video>
        PageResult result = videoApi.findByUserId(userId,page,pagesize);
        //2、从PageResult获取list    -- List<Video>
        List<Video> items = (List<Video>) result.getItems();
        if(CollUtil.isEmpty(items)) {
            return result;
        }
        List<Long> userIds = CollUtil.getFieldValues(items, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds);
        //3、将List<Video>  转化成   List<VideoVo>
        List<VideoVo> vos = new ArrayList<>();
        for (Video item : items) {
            UserInfo info = map.get(item.getUserId());//视频作者的信息
            VideoVo vo = VideoVo.init(info, item);
            vos.add(vo);
        }
        //4、将List<VideoVo>替换到PageResult的list集合
        result.setItems(vos);
        return result;
    }

    //分页查询动态列表
    public PageResult findMovements(Integer state, Long userId, Integer page, Integer pagesize) {
        //1、调用API分页查询动态    PageResult  --List<Movement>
        PageResult result =  movementApi.findAll(state,userId,page,pagesize);
        //2、从PageResult获取list    -- List<Movement>
        List<Movement> items = (List<Movement>) result.getItems();
        if(CollUtil.isEmpty(items)) {
            return result;
        }
        List<Long> userIds = CollUtil.getFieldValues(items, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds);
        //3、将List<Movement>  转化成   List<MovementVo>
        List<MovementsVo> vos = new ArrayList<>();
        for (Movement item : items) {
            UserInfo info = map.get(item.getUserId());
            MovementsVo vo = MovementsVo.init(info, item);
            vos.add(vo);
        }
        //4、将List<MovementVo>替换到PageResult的list集合
        result.setItems(vos);
        return result;
    }

    //查看动态详情
    public MovementsVo findMovementById(String movementId) {
        Movement movement = movementApi.findOneMovements(movementId);
        UserInfo userInfo = userInfoApi.select(movement.getUserId());
        return MovementsVo.init(userInfo,movement);
    }
    //查看评论列表翻页
    public PageResult movementComments(Integer page, Integer pagesize, String messageID) {
        //1、调用API分页查询动态    PageResult  --List<Movement>
        PageResult result =  commentApi.showCommentsPageResult(page,pagesize,messageID);
        //2、从PageResult获取list    -- List<Comment>
        List<Comment> list = (List<Comment>) result.getItems();
        if(CollUtil.isEmpty(list)) {
            return result;
        }
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds);
        //3、将List<CommentVo>  转化成   List<CommentVo>
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : list) {
            UserInfo info = map.get(comment.getUserId());
            CommentVo vo = CommentVo.init(info, comment);
            vos.add(vo);
        }
        //4、将List<CommentVo>替换到PageResult的list集合
        result.setItems(vos);
        return result;
    }

    /**
     * 动态通过
     * @param items
     * @return
     */
    public String pass(String[] items) {
        //遍历动态数组,修改状态
        try {
            for (String item : items) {
//                System.out.println(movementApi.findById(item));
                movementApi.updateState(item,1);
//                System.err.println("通过之后===============");
//                System.out.println(movementApi.findById(item));
            }
        } catch (Exception e) {
            //出现异常返回异常信息
            e.printStackTrace();
            return "通过失败";
        }
        //出现异常返回异常信息
        return "通过成功";

    }
    /**
     * 动态拒绝
     * @param items
     * @return
     */
    public String reject(String[] items) {
        //遍历动态数组,修改状态
        try {
            for (String item : items) {
//                System.out.println(movementApi.findById(item));
                movementApi.updateState(item,2);
//                System.err.println("拒绝之后===============");
//                System.out.println(movementApi.findById(item));
            }
            //出现异常返回异常信息
        } catch (Exception e) {
            e.printStackTrace();
            return "拒绝失败";
        }
        //出现异常返回异常信息
        return "拒绝成功";
    }

    //冻结用户
    public Map freeze(Map params) {
        Map retmap = new HashMap();
        try {
            String userId = params.get("userId").toString();
            String key = Constants.USER_FREEZE + userId;
            //构造失效时间
            Integer freezingTime = Integer.valueOf(params.get("freezingTime").toString()); //冻结时间，1为冻结3天，2为冻结7天，3为永久冻结
            int days = 0;
            if (freezingTime == 1) {
                days = 1;
            } else if (freezingTime == 2) {
                days = 7;
            } else if (freezingTime == 3) {
                days = -1;
            }
            //将数据存入mongoDB里freeze_user中
            FreezeUser freezeUser = new FreezeUser();
            freezeUser.setUserId(Long.valueOf(params.get("userId").toString()));
            freezeUser.setFreezingTime(days);
            freezeUser.setFreezingRange(Integer.valueOf(params.get("freezingRange").toString()));
            freezeUser.setReasonsForFreezing(params.get("reasonsForFreezing").toString());
            freezeUser.setFrozenRemarks(params.get("frozenRemarks").toString());
            freezeUser.setFreezeStart(System.currentTimeMillis());
            manageApi.save(freezeUser);
            //将数据存入redis
            String value = JSON.toJSONString(params);
            if (days > 0) {
                redisTemplate.opsForValue().set(key, value, days, TimeUnit.MINUTES);
            } else {
                redisTemplate.opsForValue().set(key, value);
            }
            //修改userInfo的userStatus状态
            UserInfo userInfo = userInfoApi.findById(Long.valueOf(params.get("userId").toString()));
            userInfo.setUserStatus("2");
            userInfoApi.update(userInfo);
        } catch (Exception e) {
            retmap.put("message", "操作失败");
            throw new BusinessException(retmap.get("message").toString());
        }
        retmap.put("message", "操作成功");
        return retmap;
    }

    //解冻用户
    public Map unfreeze(Map params) {
        Map retmap = new HashMap();
        try {
            //将数据存入mongoDB里unfreeze_user中
            UnFreezeUser unFreezeUser = new UnFreezeUser();
            unFreezeUser.setUserId(Long.valueOf(params.get("userId").toString()));
            unFreezeUser.setReasonsForThawing(params.get("reasonsForThawing").toString());
            manageApi.saveUnFreezeUser(unFreezeUser);
            //修改userInfo的userStatus状态
            UserInfo userInfo = userInfoApi.findById(Long.valueOf(params.get("userId").toString()));
            userInfo.setUserStatus("1");
            userInfoApi.update(userInfo);
            //删除mongoDB里freeze_user的数据
            manageApi.deleteByUserId(Long.valueOf(params.get("userId").toString()));
            //删除redis数据
            String userId = params.get("userId").toString();
            String key = Constants.USER_FREEZE + userId;
            redisTemplate.delete(key);
        } catch (Exception e) {
            retmap.put("message", "操作失败");
            throw new BusinessException(retmap.get("message").toString());
        }
        retmap.put("message", "操作成功");
        return retmap;
    }
}
